//
//  YCFriendConditionViewController.m
//  YCSchool
//
//  Created by gmall on 16/5/11.
//  Copyright © 2016年 yanglinxia. All rights reserved.
//  条件搜索

#import "YCFriendConditionViewController.h"
#import "YCPickerContainerView.h"
#import <objc/message.h>
#import "YCFindFriendViewController.h"

NSString * const YCFriendsConditionSearchDataTitle         =  @"t";
NSString * const YCFriendsConditionSearchDataValue         =  @"v";
NSString * const YCFriendsConditionSearchDataAction        = @"a";
@interface YCFriendConditionViewController ()<UITableViewDataSource,UITableViewDelegate,YCPickerContainerViewDelegate,UIPickerViewDelegate,UIPickerViewDataSource>

{
    NSString *_industryStr;
    NSString *_provinceStr;
    NSString *_cityStr;
    NSString *_areaStr;
    NSString *_distanceStr;
}
@property (readonly ,nonatomic) UITableView *tableView;
@property (readonly ,nonatomic) UIView *footView;
@property (readonly ,nonatomic) UIButton *findButton;
@property (readonly ,nonatomic) NSMutableArray *items;
@property (readonly ,nonatomic) YCPickerContainerView *pickerContainerView;
@property (readonly ,nonatomic) UIPickerView *addressPickerView;
@property (readonly ,nonatomic) NSArray *citys;
@property (readonly ,nonatomic) UIPickerView *industryPickerView;
@property (readonly ,nonatomic) NSArray *industryArray;
@property (readonly ,nonatomic) UIPickerView *distancePickerView;
@property (readonly ,nonatomic) NSArray *distanceArray;

@end


@implementation YCFriendConditionViewController


@synthesize tableView = _tableView;
@synthesize footView = _footView;
@synthesize findButton = _findButton;
@synthesize items = _items;
@synthesize pickerContainerView = _pickerContainerView;
@synthesize citys = _citys;
@synthesize addressPickerView = _addressPickerView;
@synthesize industryArray = _industryArray;
@synthesize industryPickerView = _industryPickerView;
@synthesize distanceArray = _distanceArray;
@synthesize distancePickerView = _distancePickerView;

#pragma mark - 属性获取方法

- (UITableView *)tableView
{
    if (!_tableView)
    {
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = 50;
    }
    
    return _tableView;
}

- (UIView *)footView
{
    if (!_footView)
    {
        _footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 100)];
        _footView.backgroundColor = [UIColor whiteColor];
        
        UIView *wireView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 0.3)];
        wireView.backgroundColor = [UIColor yc_colorWithUInt:0xc8c7cc];
        
        [_footView addSubview:wireView];
    }
    
    return _footView;
}

- (UIButton *)findButton
{
    if (!_findButton)
    {
        _findButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_findButton setTitle:@"查找" forState:UIControlStateNormal];
        [_findButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _findButton.backgroundColor = [UIColor blackColor];
        _findButton.layer.cornerRadius = 35 / 2;
        _findButton.titleLabel.font = [UIFont systemFontOfSize:16];
        _findButton.layer.masksToBounds = YES;
        [_findButton addTarget:self action:@selector(didTouchUpInsideFindButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _findButton;
}

- (NSArray *)citys
{
    if(!_citys)
    {
        _citys = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"allCS" ofType:@"plist"]];
    }
    return _citys;
}

- (YCPickerContainerView *)pickerContainerView
{
    if(!_pickerContainerView)
    {
        _pickerContainerView = [[YCPickerContainerView alloc] init];
        _pickerContainerView.delegate = self;
    }
    return _pickerContainerView;
}

- (UIPickerView *)addressPickerView // 地址
{
    if(!_addressPickerView)
    {
        _addressPickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 200)];
        _addressPickerView.dataSource = self;
        _addressPickerView.delegate = self;
        _addressPickerView.backgroundColor = [UIColor whiteColor];
    }
    return _addressPickerView;
}

- (UIPickerView *)industryPickerView // 行业
{
    if(!_industryPickerView)
    {
        _industryPickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 200)];
        _industryPickerView.dataSource = self;
        _industryPickerView.delegate = self;
        _industryPickerView.backgroundColor = [UIColor whiteColor];
    }
    return _industryPickerView;
}

- (UIPickerView *)distancePickerView // 距离
{
    if(!_distancePickerView)
    {
        _distancePickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 200)];
        _distancePickerView.dataSource = self;
        _distancePickerView.delegate = self;
        _distancePickerView.backgroundColor = [UIColor whiteColor];
    }
    return _distancePickerView;
}

- (NSMutableArray *)items
{
    if (!_items)
    {
        _items = [[NSMutableArray alloc] init];
        
        [_items addObject:[@{YCFriendsConditionSearchDataTitle:@"地区",
                             YCFriendsConditionSearchDataValue:@"不限",
                             YCFriendsConditionSearchDataAction:NSStringFromSelector(@selector(distanceAddressArray:))
                             } mutableCopy]];
        
        [_items addObject:[@{YCFriendsConditionSearchDataTitle:@"行业",
                             YCFriendsConditionSearchDataValue:@"不限",
                             YCFriendsConditionSearchDataAction:NSStringFromSelector(@selector(selectedIndustryIndexPath:))
                             } mutableCopy]];
        
        [_items addObject:[@{YCFriendsConditionSearchDataTitle:@"到我距离",
                             YCFriendsConditionSearchDataValue:@"不限",
                             YCFriendsConditionSearchDataAction:NSStringFromSelector(@selector(selectedDistanceIndexPath:))
                             } mutableCopy]];
    }
    
    return _items;
}

#pragma mark - 视图控制器生命周期

- (void)dealloc
{
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.title = NSLocalizedString(@"按条件查找", nil);
    [self yc_addBackBarButtonItem];
    
    [self layout];
}

#pragma mark - 自定义的方法

- (void)layout
{
    _industryArray = @[@"不限",@"农业",@"娱乐",@"服装",@"计算机",@"餐饮",@"建筑",@"设计",@"百货"];
    _distanceArray = @[@"不限",@"全城",@"10公里",@"5公里",@"3公里",@"1公里",];
    
    [self.view addSubview:self.tableView];
    self.tableView.tableFooterView = self.footView;
    [self.footView addSubview:self.findButton];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(@0);
    }];
    
    [self.findButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.footView);
        make.left.equalTo(self.footView).offset(50);
        make.right.equalTo(self.footView).offset(- 50);
        make.height.equalTo(@35);
    }];
    
}

#pragma mark - 点击行响应方法

/**
 *  选择选择地区
 *
 *  @param path 行路径
 */
- (void)distanceAddressArray:(NSIndexPath *)path
{
    [self.tableView deselectRowAtIndexPath:path animated:YES];
    
    NSUInteger pIndex = [self.citys indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
        return [obj[@"name"] isEqualToString:_provinceStr];
    }];
    
    if(pIndex < self.citys.count)
    {
        NSArray *citys = self.citys[pIndex][@"citys"];
        
        NSUInteger cIndex = [citys indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
            return [obj[@"name"] isEqualToString:_cityStr];
        }];
        
        NSArray *areas = citys[cIndex][@"ares"];
        
        NSUInteger aIndex = [areas indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
            return [obj isEqualToString:_areaStr];
        }];
        
        if(cIndex < citys.count)
        {
            [self.addressPickerView selectRow:pIndex inComponent:0 animated:NO];
            [self.addressPickerView selectRow:cIndex inComponent:1 animated:NO];
        }
        
        if (aIndex < [areas count])
        {
            [self performSelector:@selector(relayTime:) withObject:[NSNumber numberWithInteger:aIndex] afterDelay:0.1];
        }
        
    }
//    self.pickerContainerView.title = NSLocalizedString(@"选择地区", nil);
    [self.pickerContainerView showPickerView:self.addressPickerView inView:self.navigationController.view];
    
    [self.addressPickerView reloadAllComponents];
}

-(void)relayTime:(NSNumber*)_aIndex
{
    [self.addressPickerView selectRow:[_aIndex integerValue] inComponent:2 animated:NO];
}

/**
 *  选择距离
 *
 *  @param path 行路径
 */
- (void)selectedDistanceIndexPath:(NSIndexPath *)path
{
    [self.tableView deselectRowAtIndexPath:path animated:YES];
    
//    self.pickerContainerView.title = NSLocalizedString(@"离我距离", nil);
    
    [self.pickerContainerView showPickerView:self.distancePickerView inView:self.navigationController.view];
}

/**
 *  选择行业
 *
 *  @param path 行路径
 */
- (void)selectedIndustryIndexPath:(NSIndexPath *)path
{
    [self.tableView deselectRowAtIndexPath:path animated:YES];
    
//    self.pickerContainerView.title = NSLocalizedString(@"行业", nil);
    
    [self.pickerContainerView showPickerView:self.industryPickerView inView:self.navigationController.view];
}

///查找按钮
- (void)didTouchUpInsideFindButton:(UIButton *)button
{
    YCFindFriendViewController *vc = [[YCFindFriendViewController alloc] initWithSex:_industryStr Age:_distanceStr Province:_provinceStr City:_cityStr Area:_areaStr];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - UITableView delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.items.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *iden = @"IDEN";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:iden];
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:iden];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.detailTextLabel.textColor = [UIColor yc_colorWithUInt:0x757575];
        cell.textLabel.textColor = [UIColor blackColor];
        cell.textLabel.font = [UIFont systemFontOfSize:16];
        cell.detailTextLabel.font = cell.textLabel.font;
    }
    NSMutableDictionary *rowData = self.items[indexPath.row];
    cell.textLabel.text = rowData[YCFriendsConditionSearchDataTitle];
    cell.detailTextLabel.text = rowData[YCFriendsConditionSearchDataValue];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableDictionary *rowData = self.items[indexPath.row];
    NSString *actionString = rowData[YCFriendsConditionSearchDataAction];
    if(actionString)
    {
        SEL action = NSSelectorFromString(actionString);
        if([self respondsToSelector:action])
        {
            void (* gm_objc_msgSend)(id,SEL,id) = (void (*)(id,SEL,id))objc_msgSend;
            gm_objc_msgSend(self,action,indexPath);
        }
    }
}

#pragma mark - UIPickerView delegate

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    if (pickerView == self.addressPickerView)
    {
        return 3;
    }
    
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    
    if (pickerView == self.addressPickerView)
    {
        if (component == 0)
        {
            NSUInteger rows = self.citys.count;
            
            return rows;
        }
        else if (component == 1)
        {
            NSDictionary *pro = self.citys[[pickerView selectedRowInComponent:0]];
            NSUInteger rows = [pro[@"citys"] count];
            
            return rows;
        }
        else
        {
            NSInteger selectedRow = [pickerView selectedRowInComponent:0];
            NSArray *citys = self.citys[selectedRow][@"citys"];
            selectedRow = [pickerView selectedRowInComponent:1];
            NSArray *ares = citys[selectedRow][@"ares"];
            NSUInteger rows = [ares count];
            return rows;
        }
    }
    if (pickerView == self.industryPickerView)
    {
        return self.industryArray.count;
    }
    
    return self.distanceArray.count;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    NSString *title;
    if (pickerView == self.addressPickerView)
    {
        if(component == 0)
        {
            title = self.citys[row][@"name"];
            _provinceStr = title;
        }
        else if(component == 1)
        {
            NSArray *citys = self.citys[[pickerView selectedRowInComponent:0]][@"citys"];
            if(row < citys.count)
            {
                title = citys[row][@"name"];
                _cityStr = title;
            }
        }
        else
        {
            NSArray *areas = self.citys[[pickerView selectedRowInComponent:0]][@"citys"][[pickerView selectedRowInComponent:1]][@"ares"];
            if(row < areas.count)
            {
                title = areas[row];
                _areaStr = title;
            }
        }
    }
    else if (pickerView == self.industryPickerView)
    {
        title = _industryArray[row];
    }
    else
    {
        title = _distanceArray[row];
    }
    
    return title;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (pickerView == self.addressPickerView)
    {
        if (component == 0)
        {
            [pickerView reloadAllComponents];
            [pickerView selectRow:0 inComponent:1 animated:YES];
            [pickerView selectRow:0 inComponent:2 animated:YES];
        }
        else if (component == 1)
        {
            [pickerView reloadAllComponents];
            [pickerView reloadComponent:2];
            [pickerView selectRow:0 inComponent:2 animated:YES];
        }
        else
        {
            [pickerView reloadAllComponents];
        }
    }
    if (pickerView == self.industryPickerView)
    {
        
        _industryStr = _industryArray[row];
        
    }
    if (pickerView == self.distancePickerView)
    {
        
        _distanceStr = _distanceArray[row];
        
    }
}

// pickerView点击确定时
- (void)pickerContainerViewDidDone:(YCPickerContainerView *)containerView
{
    if (containerView.pickerView == self.addressPickerView)
    {
        NSString *areaStr = [NSString stringWithFormat:@"%@ %@ %@",_provinceStr,_cityStr,_areaStr];
        self.items[0][YCFriendsConditionSearchDataValue] = areaStr;
    }
    if (containerView.pickerView == self.industryPickerView)
    {
        if (!_industryStr)
        {
            _industryStr = @"不限";
        }
        self.items[1][YCFriendsConditionSearchDataValue] = _industryStr;
        if ([_industryStr isEqualToString:@"不限"])
        {
            _industryStr = nil;
        }
        
    }
    if (containerView.pickerView == self.distancePickerView)
    {
        if (!_distanceStr)
        {
            _distanceStr = @"不限";
        }
        self.items[2][YCFriendsConditionSearchDataValue] = _distanceStr;
        
        if ([_distanceStr isEqualToString:@"不限"])
        {
            _distanceStr = nil;
        }
        
    }
    [self.tableView reloadData];
}



@end
